package it.davial.mgwt.client.mvp;

import it.davial.mgwt.client.ClientFactory;
import it.davial.mgwt.client.activities.about.AboutActivity;
import it.davial.mgwt.client.activities.about.AboutPlace;
import it.davial.mgwt.client.activities.patient.PatientActivity;
import it.davial.mgwt.client.activities.patient.PatientPlace;
import it.davial.mgwt.client.activities.patient.detail.PatientDetailActivity;
import it.davial.mgwt.client.activities.patient.detail.PatientDetailPlace;
import it.davial.mgwt.client.activities.picture.PictureActivity;
import it.davial.mgwt.client.activities.picture.PicturePlace;
import it.davial.mgwt.client.activities.visit.VisitActivity;
import it.davial.mgwt.client.activities.visit.VisitPlace;
import it.davial.mgwt.client.test.TestActivity;
import it.davial.mgwt.client.test.TestPlace;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.place.shared.Place;

public class TabletMainActivityMapper implements ActivityMapper {

	private final ClientFactory clientFactory;
	
	private Place lastPlace;
	private AboutActivity about;
	private PictureActivity picture;
	private PatientActivity patient;
	private PatientDetailActivity patientDetail;
	private VisitActivity visit;

	public TabletMainActivityMapper(ClientFactory clientFactory) {
		this.clientFactory = clientFactory;

	}

	@Override
	public Activity getActivity(Place place) {
		Activity activity = getActivity(lastPlace, place);
		lastPlace = place;
		return activity;

		
	}

	
	private Activity getActivity( Place lastPlace, Place newPlace){
		
		if ( newPlace instanceof PicturePlace )
			return getPictureActivity();

		if ( newPlace instanceof AboutPlace )
			return getAboutActivity();

		if ( newPlace instanceof PatientPlace )
			return getPatientActivity();

		if ( newPlace instanceof PatientDetailPlace )
			return getPatientDetailActivity((PatientDetailPlace) newPlace);

		if ( newPlace instanceof VisitPlace )
			return getVisitActivity();
		if ( newPlace instanceof TestPlace )
			return new TestActivity(clientFactory);
		
		return null;

	}
	
	private AboutActivity getAboutActivity(){
		if ( about == null )
			about = new AboutActivity(clientFactory);
		return about;
	}

	private PatientActivity getPatientActivity(){
		if ( patient == null )
			patient = new PatientActivity(clientFactory);
		return patient;
	}

	private PatientDetailActivity getPatientDetailActivity(PatientDetailPlace place){
		if ( patientDetail == null )
			patientDetail = new PatientDetailActivity(clientFactory);
		if ( place != null )
			patientDetail.setPatient(place.getPatient());
		else
			patientDetail.setPatient(null);
		return patientDetail;
	}

	private VisitActivity getVisitActivity(){
		if ( visit == null )
			visit = new VisitActivity(clientFactory);
		return visit;
	}

	private PictureActivity getPictureActivity(){
		if ( picture == null )
			picture = new PictureActivity(clientFactory);
		return picture;
	}

}
